package objects
{
	import flash.geom.Point;
	import objects.cicleItem.cicleItemCanon;
	import starling.core.Starling;
	import starling.display.Image;
	import starling.display.MovieClip;
	import starling.display.Sprite;
	import starling.events.Event;
	import starling.filters.BlurFilter;
	import com.greensock.*;
	import com.greensock.easing.*;
	import objects.BoomManager;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;
	import starling.filters.BlurFilter;
	import starling.textures.Texture;
	
	/**
	 * ...
	 * @author ...Vượng
	 */
	
	public class Canon extends MyObject
	{
		public var m_boomManager:BoomManager;
		public var m_circleCollision:Image;
		public var m_testChoose:Boolean;
		public var m_cicleItem:cicleItemCanon;
		public var m_sprite:Sprite;
		public var m_range: Number;
		public var m_cointTotal:Number;
		public var m_isShoot : Boolean;
		public var m_isSwapShoot : Boolean;
		
		public var m_timeShoot : Number; //use for swawp frames
		public var m_timeCooldownShoot : Number; // thoi gian giua 2 lan ban'
		public var m_firstShoot : Number;
		
		public function Canon(_sprite:Sprite, _pos:Point,_coint:int)
		{
			
			m_isSwapShoot = false; 
			m_sprite = _sprite;
			m_pos = _pos;
			m_level = 1;
			m_cicleItem = new cicleItemCanon(m_sprite, m_pos);
			this.addEventListener(Event.ADDED_TO_STAGE, init);
			m_sprite.addEventListener(TouchEvent.TOUCH, onTouch);
			m_sprite.addChild(this);
			setInfoFromCoint(_coint);
			m_cointTotal = _coint;
		}
		
		private function onTouch(e:TouchEvent):void
		{
			if (database.instance.m_testTouch == true)
			{
			var touch:Touch = e.getTouch(stage);
			if (touch)
			{
				var _pointTouch:Point = new Point(touch.globalX, touch.globalY);
				if (touch.phase == TouchPhase.BEGAN)
				{
					if (m_spriteMovie.bounds.containsPoint(_pointTouch) == true)
					{
						m_cicleItem.showCoint(m_cointTotal);
						m_cicleItem.clockAndUnclock();
						m_cicleItem.showCoint(m_cointTotal);
						if (m_testChoose == false)
						{
							m_testChoose = true;
							m_sprite.setChildIndex(this, m_sprite.numChildren);
							m_sprite.setChildIndex(m_cicleItem, m_sprite.numChildren);
						}
						else
						{
							m_testChoose = false;
						}
					}
					else
					{
						m_cicleItem.returnResult(_pointTouch);
						m_testChoose = false;
						if (m_cicleItem.m_result == -1)
						{
							m_testChoose = true;
						}
					}
				}
				
				else if (touch.phase == TouchPhase.ENDED)
				{
					
				}
				
				else if (touch.phase == TouchPhase.HOVER)
				{
					if (m_spriteMovie.bounds.containsPoint(_pointTouch) == true)
					{
						m_spriteMovie.filter = BlurFilter.createDropShadow(0, 0, 0xff0000, 1, 1, 0.5);
						
					}
					else
					{
						m_spriteMovie.filter = null;
					}
					
					m_cicleItem.blurFilter(_pointTouch);
				}
			}
			}
		}
		
		private function init(event:Event):void
		{
			this.removeEventListener(Event.ADDED_TO_STAGE, init);
			m_minDamage = database.instance.RESULTCANONARRAY[0];
			m_maxDamage = m_minDamage * 2;
			
			m_range = database.instance.RESULTCANONARRAY[6];
			m_circleCollision = new Image(Assets.getTexture("circle1"));
			m_circleCollision.pivotX = m_circleCollision.width / 2;
			m_circleCollision.pivotY = m_circleCollision.height / 2;
			
			m_circleCollision.x = m_pos.x;
			m_circleCollision.y = m_pos.y;
			
			m_circleCollision.alpha = 0.5;
			
			m_circleCollision.scaleX = m_range;
			m_circleCollision.scaleY = m_range;
			m_circleCollision.alpha = 0;
			
			this.addChild(m_circleCollision);
			
			m_choosedEnemy = null;
			
		    m_firstShoot = 0;
			m_isShoot = false;
			m_timeShoot = 0;
			m_spriteMovie = new MovieClip(Assets.getSpriteSheet().getTextures("canonstandlv_1_"), 7); //4 frame 1 s, total 2 frame->0.5s
			this.setAnchorPoint();
			m_spriteMovie.scaleX = 0.6;
			m_spriteMovie.scaleY = 0.6;
			this.setPos(m_pos);
			this.addChild(m_spriteMovie);
			Starling.juggler.add(m_spriteMovie);
			
			//time cooldown to shoot
			m_coolDown = 1.5;
			m_timeCooldownShoot = 1.5;
			//speed's Boom from this Canon
			m_maxVelocity = 3;
			m_damage = 1;
			
			m_collision = false;
			m_boomManager = new BoomManager();
			
		
		}
		
		public function shoot(enemy:MyObject, dt:Number):void
		{
			
			var totarget:Point = ccpSub(enemy.m_pos, new Point(m_pos.x, m_pos.y - 30));
			var a:Number = ccpDot(enemy.m_velocity, enemy.m_velocity) - (m_maxVelocity * m_maxVelocity);
			var b:Number = 2 * ccpDot(enemy.m_velocity, totarget);
			var c:Number = ccpDot(totarget, totarget);
			
			var p:Number = -b / (2 * a);
			var q:Number = Math.sqrt((b * b) - 4 * a * c) / (2 * a);
			
			var t1:Number = p - q;
			var t2:Number = p + q;
			var t:Number;
			if (t1 > t2 && t2 > 0)
			{
				t = t2;
			}
			else
			{
				t = t1;
			}
			var aimSpot:Point = ccpAdd(enemy.m_pos, ccpMult(enemy.m_velocity, t));
			var BoomPath:Point = ccpSub(aimSpot, m_pos);
			var timeToImpact:Number = BoomPath.length / m_maxVelocity / 60;
			

			m_boomManager.addBoom(new Boom(this, new Point(m_pos.x, m_pos.y - 30), timeToImpact, m_maxVelocity, m_minDamage, m_maxDamage));
			
			for (var i:int = 0; i < m_boomManager.getListBoom().length; i++)
			{
				m_boomManager.getBoom(i).setTarget(aimSpot);
			}
		}
		
		override public function update(dt:Number):void
		{
			if (m_isShoot == true)//ban'
			{
				m_isShoot = false;
				m_isSwapShoot = true;
				swapFrames (m_spriteMovie, Assets.getSpriteSheet().getTextures("canonshootlv_" + m_level +"_") );
			}
			
			
			if (m_isSwapShoot == true)// dem' time xem ban' xong chua
			{
			    m_timeShoot += dt;		
			}
			if (m_isShoot == false)//finish animation shoot
			{
				if (m_timeShoot >= m_spriteMovie.totalTime && m_isSwapShoot ==true)
				{
				  m_timeShoot = 0;
				  m_isSwapShoot = false;
				  swapFrames (m_spriteMovie, Assets.getSpriteSheet().getTextures("canonstandlv_" + m_level + "_") );
				}
			}
			
			if (m_testChoose == true)
			{
				if (m_cicleItem.m_spriteMovie.alpha < 1)
				{
					m_circleCollision.alpha =0.3;
				}
				m_cicleItem.alphaUp();
			}
			else
			{
				m_cicleItem.alphaDown();
				m_circleCollision.alpha = 0;
			}
			m_boomManager.update(dt);
			
			if (m_choosedEnemy != null && m_choosedEnemy.m_hp <= 0) // quai' het' mau thi huy
			{
				m_choosedEnemy = null;
				m_collision = false;
			}
			
			if (m_choosedEnemy != null && m_collision == true) // check and shoottttttt
			{
				m_coolDown += dt;
				if (m_coolDown >= m_timeCooldownShoot)
				{
					m_coolDown = 0;
					
					
					shoot(m_choosedEnemy, dt);
				}
				if (m_firstShoot == 0)
				{
					m_isShoot = true;
					m_firstShoot ++;
				}
				if ( m_coolDown >= (m_timeCooldownShoot - m_spriteMovie.totalTime) && m_isSwapShoot ==false)
				{
					m_isShoot = true;
				}
			}
			if (m_choosedEnemy != null && m_collision == true) //ra khoi area thi release enemy
			{
				if (m_circleCollision.bounds.intersects(m_choosedEnemy.getRect()) == false)
				{
					m_choosedEnemy = null;
					m_collision = false;
				}
			}
			
			if (ManagerEffect.instance.ListEff.length > 0)
			{
				m_boomManager.Collision(m_choosedEnemy, dt);
			}	
		}
		public function setInfoFromCoint(_coint:int):void
		{	
			m_cicleItem.setCicleInfo();
			m_cicleItem.showCoint(_coint);
		}
		public function levelUpAndSale(dt:Number, _coint:int):int
		{
			if (m_cicleItem.m_result == 1)
			{
				if ( m_cicleItem.m_baseItem[0].m_coint <= _coint)
				{
					//nang cap cac thong so
					m_level += 1;
					
					if (m_level == 2)
					{
						m_range += 0.2;
						m_circleCollision.scaleX = m_range;
			            m_circleCollision.scaleY = m_range;
						m_minDamage =  database.instance.RESULTCANONARRAY[2];
						m_maxDamage = m_minDamage * 2;
					}
					else if (m_level == 3)
					{
						m_range += 0.2;
						m_circleCollision.scaleX = m_range;
			            m_circleCollision.scaleY = m_range;
						m_minDamage = database.instance.RESULTCANONARRAY[4];
						m_maxDamage = m_minDamage * 2;
					}
					
					//cap nhat cac thong so
					_coint -= m_cicleItem.m_baseItem[0].m_coint;
					m_cicleItem.m_level = m_level;
					setInfoFromCoint(_coint);
					
					
					if (m_isShoot == false && m_isSwapShoot == false)
					{
						swapFrames (m_spriteMovie,  Assets.getSpriteSheet().getTextures("canonstandlv_" + m_level + "_") );
					}
					
					//this.setAnchorPoint();
					//this.setPos(m_pos);

					//ket thuc
					m_cicleItem.m_result = 0;
					
					//tra ve coint
					return _coint;
				}
			}
			if (m_cicleItem.m_result == 2)
			{
				return _coint -= m_cicleItem.m_baseItem[1].m_coint;
			}
			return _coint;
		}
		public function swapFrames(clip:MovieClip, textures:Vector.<Texture>):void 
		{
 
	      // remove all frame but one, since a MovieClip is not allowed to have 0 frames
		  
		  

          	while(clip.numFrames > 1){
		    clip.removeFrameAt(0);
	        }
 
	         // add new frames
	          for each (var texture:Texture in textures){
		       clip.addFrame(texture);
	          }
 
	        // remove that last previous frame
           	clip.removeFrameAt(0);
 
	         // set to frame 1
	        clip.currentFrame = 1;
		 }
		override public function Collision(_enemy:MyObject, dt:Number):void
		{
			
				if (this.TestCollisionelip_Point(_enemy.m_pos, m_circleCollision) == true)
				{
					if (m_choosedEnemy == null && m_collision == false)
					{
						m_choosedEnemy = _enemy;
						m_collision = true;
					}
				}
			
		}
		
		public function setAnchorPoint():void
		{
			m_spriteMovie.pivotX = m_spriteMovie.width / 2;
			m_spriteMovie.pivotY = m_spriteMovie.height / 2;
		}
		
		public function setPos(_pos:Point):void
		{
			m_spriteMovie.x = _pos.x;
			m_spriteMovie.y = _pos.y;
		}
		
		public function setScale(_scale:Number):void
		{
			m_spriteMovie.scaleX = _scale;
			m_spriteMovie.scaleY = _scale;
		}
		
		public function releaseFull(_listContain:Array,_index:int):void
		{	
			this.removeChildren();
			m_cicleItem.release();
			m_sprite.removeChild(this);
			_listContain.splice(_index, 1);
		}
	}

}
